<?php
/**
 * 设计师服务合同
 */
namespace Beerus\Modules\DesignerService\Controllers;

use App\Http\Controllers\Controller;
use App\Pockets\GridDataModel as pGridDataModel;
use Beerus\Modules\DesignerService\Actions\CreateKeywords;
use Biz\pockets\excel\DownExcel;
use Doraemon\model\Admin\BeerUsUser;
use Doraemon\model\DecoCompany;
use Doraemon\model\Designer;
use Doraemon\model\DesignerDecorationTie;
use Doraemon\model\DesignerOperatorBind\DesignerOperatorBind;
use Doraemon\model\Member;
use Doraemon\model\Member as mMember;
use Doraemon\service\DesignerService\Contract;
use Doraemon\service\User;
use Doraemon\service\User as sUser;
use Doraemon\tools\FileOSSGoTool;
use Encore\Admin\Facades\Admin;
use Encore\Admin\Grid;
use Illuminate\Http\Request;
use Doraemon\model\DesignerService\Contract as mContract;
use Encore\Admin\Widgets\Form;
use Encore\Admin\Widgets\Tab;
use Illuminate\Support\MessageBag;
use Encore\Admin\Layout\{Column, Row, Content};
use Encore\Admin\Widgets\Box;
use Doraemon\service\DesignerService\ServiceSpotService;
use Doraemon\tools\Log;

class ContractController extends Controller {
    const PAGE_SIZE = 5;

    const MAX_AUDIT_FEEDBACK_LEN = 100;

    const AUDIT_STATUS_TXT = [
        mContract::AUDIT_WAIT => '待审核',
        mContract::AUDIT_FAIL => '认证失败',
        mContract::AUDIT_SUCCESS => '认证成功',
        mContract::AUDIT_REVOKE => '已撤销',
        mContract::AUDIT_OLD => '已作废'
    ];
    public function __construct()
    {
        parent::__construct();
        Admin::script('$(".pjax-container").attr("id","pjax-container");');
    }

    /**
     * 大赛报名列表
     * @param Request $request
     * @param Content $content
     * @return Content
     */
    public function index(Request $request, Content $content) {
        $pageSize = $request->input('per_page', self::PAGE_SIZE);
        $page = $request->input('page', 1);
        $request = $request->all();
        if (!empty($request['uid'])) {
            $condition['uid'] = $request['uid'];
        }
        if (!empty($request['nick'])) {
            $uid = sUser::getUidByNick($request['nick']);
            $condition['uid'] = $uid ?? 0;
        }
        if (!empty($request['audit_status'])) {
            $condition['audit_status'] = $request['audit_status'];
        }
        if (!empty($request['add_time']['start'])) {
            $condition['add_time[>=]'] = strtotime($request['add_time']['start']);
        }
        if (!empty($request['add_time']['end'])) {
            $condition['add_time[<=]'] = strtotime($request['add_time']['end']);
        }
        if (!empty($request['audit_time']['start']) || !empty($request['audit_time']['end'])) {
            $condition['audit_time[>]'] = 0;
        }
        if (!empty($request['audit_time']['start'])) {
            $condition['audit_time[>=]'] = strtotime($request['audit_time']['start']);
        }
        if (!empty($request['audit_time']['end'])) {
            $condition['audit_time[<=]'] = strtotime($request['audit_time']['end']);
        }
        $condition['data_status'] = mContract::STATUS_NORMAL;
        return $content
            ->header('已认证合同列表')
            ->row(self::indexGrid($condition, $page, $pageSize));
    }


    /**
     * 表格展示部分
     * @param $condition
     * @return Grid
     */
    public function indexGrid($condition, $page, $pageSize) {
        $total = mContract::count($condition);
        $condition['ORDER'] = ['id' => 'DESC'];
        $condition['LIMIT'] = [
            ($page - 1) * $pageSize,
            $pageSize
        ];
        $list = mContract::select('*', $condition);
        $this->formatList($list);
        $gridModel = new pGridDataModel($list, $total, [
            'perPage' => self::PAGE_SIZE,
        ]);

        $search_params = http_build_query($condition);

        return Admin::grid(
            $gridModel,
            function (Grid $grid) use ($gridModel,$search_params) {
                $grid->paginate($gridModel->getPerPage());
                $grid->disableCreateButton();
                $grid->disableExport();
                $grid->disableRowSelector();
                // 添加导出按钮
                $grid->tools(function (Grid\Tools $tool) use ($grid, $search_params) {
                    $url = url('/admin/DesignerService/white/export?'. $search_params);
                    $button = '<div class="btn-group download" style="margin-right: 10px">
                        <a class="btn btn-sm btn-primary" target="_blank" href="'.$url.'">
                        <i class="fa fa-download"></i>
                        <span class="hidden-xs">导出合同信息表</span></a>
                    </div>';
                    $tool->append($button);
                });
                // todo 暂时去除
//                $grid->tools(function (Grid\Tools $tools) {
//                    $tools->append(new CreateKeywords());
//                });

                $grid->filter(function (Grid\Filter $filter) {
                    $filter->disableIdFilter();
                    $filter->column(1/2, function ($filter) {
                        $filter->equal('nick', '设计师昵称');
                        $filter->equal('uid', '设计师uid');
                        $filter->equal('audit_status', '认证状态')->radio(self::AUDIT_STATUS_TXT);
                    });
                    $filter->column(1/2, function ($filter) {
                        $filter->between('add_time', '提交时间')->datetime();
                        $filter->between('audit_time', '认证时间')->datetime();
                    });
                    $filter->expand();
                });

                $grid->column('id', '合同id');
                $grid->column('file_name', '合同文件')->display(function () {
                    $isView = $this->audit_status == mContract::AUDIT_WAIT ? 0 : 1;
                    $skipUrl = '/admin/DesignerService/contract/'.$this->id.'/edit/' . $isView;
                    return "<a href='{$skipUrl}'><span style='color:#418EFF'>{$this->file_name}</span></a>";
                });
                $grid->column('nick', '设计师名称');
                $grid->column('uid', '设计师uid');
                $grid->column('operator_name', '对接运营');
                $grid->column('add_time', '提交时间')->display(function () {
                    return date('Y-m-d H:i:s', $this->add_time);
                });
                $grid->column('auth_status', '认证状态')->display(function () {
                    $auditStatusTxt = self::AUDIT_STATUS_TXT[$this->audit_status];
                    switch ($this->audit_status) {
                        case mContract::AUDIT_WAIT:
                            $color = '#f39c12';
                            break;
                        case mContract::AUDIT_SUCCESS:
                            $color = '#00c0ef';
                            break;
                        default:
                            $color = 'black';
                    }
                    $auditStatusTxt = '<span style="color: ' . $color . '">' . $auditStatusTxt . '</span>';
                    if ($this->audit_status == mContract::AUDIT_FAIL) {
                        $auditStatusTxt .= '<br/>理由：'.$this->audit_feedback;
                    }
                    return $auditStatusTxt;
                })->width(250);
                $grid->column('audit_time', '认证时间')->display(function () {
                    if ($this->audit_time == 0) {
                        return '无';
                    } else {
                        return date('Y-m-d H:i:s', $this->audit_time);
                    }
                });
                $grid->column('admin_name', '操作人');
                $grid->actions(function (Grid\Displayers\Actions $actions) {
                    $actions->disableEdit();
                    $actions->disableView();
                    $actions->disableDelete();
                    if ($actions->row->audit_status == mContract::AUDIT_WAIT) {
                        $actions->prepend('<a class="setTop label label-warning" style="margin: 4px" data-id="" href="/admin/DesignerService/contract/'.$actions->row->id.'/edit/0">去认证</a>');
                    } else {
                        $actions->prepend('<a class="setView label label-info" style="margin: 4px"  href="/admin/DesignerService/contract/' . $actions->row->id . '/edit/1">查看</a>');
                    }
                });
            }
        );
    }

    public function formatList(&$aList) {
        $aUids = array_unique(array_column($aList, 'uid'));
        $aUserList = sUser::getUserInfoByIds($aUids);
        $aOperatorList = DesignerOperatorBind::select('*', [
            'uid' => $aUids,
            'data_status' => DesignerOperatorBind::STATUS_NORMAL
        ]);
        $aUserList = !empty($aUserList) ? array_column($aUserList, 'nick', 'uid') : [];
        $aOperatorList = !empty($aOperatorList) ? array_column($aOperatorList, 'admin_name', 'uid') : [];
        $aAdminIds = array_unique(array_column($aList, 'admin_id'));
        $aAdminList = BeerUsUser::select('*', ['id' => $aAdminIds]);
        $aAdminList = !empty($aAdminList) ? array_column($aAdminList, 'username', 'id') : [];
        foreach ($aList as &$aItem) {
            $aItem['nick'] = $aUserList[$aItem['uid']] ?? '';
            $aItem['operator_name'] = $aOperatorList[$aItem['uid']] ?? '无';
            $aItem['admin_name'] = $aAdminList[$aItem['admin_id']] ?? '无';
        }
    }

    public function edit(Request $request, Content $content, $id = 0, $isView = 0) {
        Admin::style('#app > row:first > fields-group > form-group > div:first {width:100%;}');
        $aContractInfo = mContract::getContractInfo($id);
        return $content->header('审核合同')
            ->breadcrumb(
                [
                    'text' => '合同列表',
                    'url' => route('contract.list')
                ],
                ['text' => '审核合同'],
            )
            ->row(function (Row $row) use ($aContractInfo, $isView) {
                $row->column(8, function (Column $column) use ($aContractInfo) {
                    $form = new Form();
//                    $url = "https://designer.gray4.haohaozhu.me/pdf-viewer?contractId={$aContractInfo['id']}";
                    $url = "https://designer.haohaozhu.cn/pdf-viewer?contractId={$aContractInfo['id']}";
                    $form->html('<iframe name="preview" src="' . $url . '" style="width:100%; height:1000px;margin-top:10px;"></iframe>')->setWidth(12,0);
                    $form->disableSubmit();
                    $form->disableReset();
                    $column->append((new Box(__('预览'), $form))->style('success'));
                });
                $row->column(4, function (Column $column) use ($aContractInfo, $isView) {
                    $form = $this->getAuditForm($aContractInfo, $isView);
                    $sTitle = $isView ? '查看' : '新建';
                    $column->append((new Box(__($sTitle), $form))->style('success'));
                });
            });
    }

    /**
     * 获取审核form
     * @param $iContractId
     * @param false $bIsView 是否仅查看
     * @return Form
     */
    protected function getAuditForm($aContractInfo, $bIsView = false) {
        Admin::script($this->setScript());
        $form = new Form($aContractInfo);
        $form->text('id', 'ID')->readOnly();
        if ($bIsView) {
            $form->radio('audit_status', '认证')->options([
                mContract::AUDIT_SUCCESS => '认证通过',
                mContract::AUDIT_FAIL => '认证失败'
            ])->default($aContractInfo['audit_status'])->readonly();
            if ($aContractInfo['audit_status'] == mContract::AUDIT_FAIL) {
                $form->textarea('audit_feedback', '失败理由')->readonly();
            }
            if (in_array($aContractInfo['audit_status'], [mContract::AUDIT_SUCCESS, mContract::AUDIT_FAIL])) {
                $sAdminName = BeerUsUser::get('username', ['id' => $aContractInfo['admin_id']]);
                $form->text('admin_name', '操作人')->default($sAdminName)->readonly();
                $sAuditDate = date('Y-m-d H:i:s', $aContractInfo['audit_time']);
                $form->text('audit_date', '操作时间')->default($sAuditDate)->readonly();
            }
            $form->disableReset();
            $form->disableSubmit();
        } else {
            $form->radio('audit_status', '认证')->options([
                mContract::AUDIT_SUCCESS => '认证通过',
                mContract::AUDIT_FAIL => '认证失败'
            ])->when(mContract::AUDIT_FAIL, function (Form $form) {
                $form->textarea('audit_feedback', '失败理由');
            });
        }
        $form->disablePjax();
        return $form;
    }

    /*设置scirpt
    *
    * */
    private function setScript() {
        return <<<SCRIPT
            $(':submit').click(function(e){
                var is_pass = $('input[name=audit_status]').eq(0).parent().attr('aria-checked');
                var is_fail = $('input[name=audit_status]').eq(1).parent().attr('aria-checked')
                var audit_status = 0;
                if (is_pass == 'true') {
                    audit_status = $('input[name=audit_status]').eq(0).val();
                }
                if (is_fail == 'true') {
                    audit_status = $('input[name=audit_status]').eq(1).val();
                }
                let url = '/admin/DesignerService/contract/save';
                let params = {
                    id: $('#id').val(),
                    audit_status:audit_status,
                    audit_feedback:$('textarea[name=audit_feedback]').val(),
                };
                console.log(params);
                $.post(url, params, function (result) {
                    console.log(result)
                    if (result.status == true) {
                        layer.msg('提交成功');
                        setTimeout(function () {
                            window.location.href = "/admin/DesignerService/contract";
                        }, 1000);
                    } else {
                        layer.msg(result.message);
                    }
                });
            })
        SCRIPT;
    }

    public function save(Request $request) {
        $request = $request->all();
        if (!in_array($request['audit_status'], [mContract::AUDIT_FAIL, mContract::AUDIT_SUCCESS])) {
            return response()->json([
                'status' => false,
                'message' => "审核状态有误",
            ]);
        }
        if ($request['audit_status'] == mContract::AUDIT_FAIL && empty($request['audit_feedback'])) {
            return response()->json([
                'status' => false,
                'message' => "请填写认证失败理由，一百字以内",
            ]);
        }
        $auditFeedbackLen = mb_strlen($request['audit_feedback']);
        if ($request['audit_status'] == mContract::AUDIT_FAIL
            && ($auditFeedbackLen > self::MAX_AUDIT_FEEDBACK_LEN || $auditFeedbackLen <= 0)) {
            return response()->json([
                'status' => false,
                'message' => "请填写认证失败理由，一百字以内",
            ]);
        }
        $aContractInfo = mContract::getCuInAuditContractById($request['id']);
        if (empty($aContractInfo)) {
            return response()->json([
                'status' => false,
                'message' => "您要审核的合同不存在",
            ]);
        }
        // 有认证通过的，则将历史认证通过的更改为4=已作废
        if ($request['audit_status'] == mContract::AUDIT_SUCCESS) {
            mContract::updateCurAuditSuccess2Old($aContractInfo);
        }
        // 历史认证失败无需处理，在前台，用户上传合同时，会把历史认证失败is_show改为0
        $data = [
            'audit_status' => $request['audit_status'],
            'audit_feedback' => $request['audit_feedback'],
            'audit_time' => time(),
            'admin_id' => Admin::user()->id
        ];
        if (!mContract::updateInfo($data, ['id' => $request['id'], 'audit_status' => mContract::AUDIT_WAIT])) {
            return response()->json([
                'status' => false,
                'message' => "提交失败，该合同已被覆盖",
            ]);
        }
        Contract::sendAuditRet2Designer($aContractInfo['uid'], $request['audit_feedback']);
        $oldList = mContract::getUserOldContractList($aContractInfo['uid']);
        Log::info('oldList',['oldList'=>$oldList]);
        if(empty($oldList)){
            ServiceSpotService::spotAdd($aContractInfo['uid']);
        }
        return response()->json([
            'status' => true,
        ]);
    }

    public function export(Request $request)
    {
        $params = $request->all();

        $list = mContract::select('*', $params);
        $this->formatList($list);

        $data = [];
        foreach ($list as $key => $item) {
            //处理主要服务地区
            $designer_main_info = Designer::getDesignerSomeInfo(['main_area_code','main_area_name'],$item['uid']);
            $main_area_name = $designer_main_info['main_area_name'];
            //处理合同跳转链接
            $isView = $item['audit_status'] == mContract::AUDIT_WAIT ? 0 : 1;
            $skipUrl = 'https://beerus.haohaozhu.me/admin/DesignerService/contract/'.$item['id'].'/edit/' . $isView;
            $data[] = [
                'nick' => $item['nick'],
                'uid' => $item['uid'],
                'area' => $main_area_name,
                'link' => $skipUrl,
                'operator_name' => $item['operator_name'],
                'addtime' => date('Y-m-d H:i:s', $item['add_time']),
                'audit_time' => date('Y-m-d H:i:s', $item['audit_time']),
                'admin_name' => $item['admin_name'],
            ];
        }

        // 设置列宽
        $letter = range('A', 'N');
        $header = [
            '设计师名称', '设计师uid','设计师主要服务地区', '合同链接', '对接运营','提交时间', '认证时间', '操作人'
        ];
        $excel = new DownExcel();
        $excel->setFileName('已认证合同列表 - ' . date('YmdHis'));
        $excel->setSheetTitle('已认证合同列表');

        // 设置列宽
        $width = [
            'A' => 12,
            'B' => 15,
            'C' => 20,
            'D' => 30,
            'E' => 30,
            'F' => 30,
            'G' => 30,
            'H' => 30,
        ];

        $excel->setWidth($width);
        $excel->setDefaultStyleAlignment();

        foreach ($header as $key => $value) {
            // 设置字体
            $excel->setFrontName($letter[$key]);
            // 设置加粗
            $excel->setFrontBold("$letter[$key]1");
            // 设置大小
            $excel->setFrontSize($letter[$key]);
        }

        $excel->create($data, $header);
    }

}
